import React, { useState, useEffect, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {
  Card,
  Typography,
  Input,
  Button,
  Tooltip,
  message,
  Spin,
  Empty,
  Tag,
} from 'antd';
import {
  MessageOutlined,
  SendOutlined,
  SearchOutlined,
  ClearOutlined,
  HeartOutlined,
  BulbOutlined,
  MenuOutlined,
  MenuFoldOutlined,
} from '@ant-design/icons';
import chatService from '../../services/ChatService';
import SessionList from '../SessionList/SessionList';
import '../../styles/ChatBot.css';

const { Title } = Typography;
const { TextArea } = Input;

const ChatBot = () => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [enableSearch, setEnableSearch] = useState(false);
  const [enablePersonalization, setEnablePersonalization] = useState(false);
  const [enableDeepThinking, setEnableDeepThinking] = useState(false);
  const [chatStatus, setChatStatus] = useState(null);
  const [currentSessionId, setCurrentSessionId] = useState(null);
  const [sessionListVisible, setSessionListVisible] = useState(true);
  const [sessionListRefreshTrigger, setSessionListRefreshTrigger] = useState(0);
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 初始化：获取聊天状态
  useEffect(() => {
    const initChat = async () => {
      try {
        // 获取聊天状态
        const statusResult = await chatService.getChatStatus();
        if (statusResult.success) {
          setChatStatus(statusResult.data);
        }
      } catch (error) {
        console.error('初始化聊天失败:', error);
      }
    };

    initChat();
  }, []);

  // 加载会话历史
  const loadSessionHistory = async (sessionId) => {
    if (!sessionId) {
      setMessages([]);
      return;
    }

    try {
      const historyResult = await chatService.getChatHistory(sessionId);
      if (historyResult.success && historyResult.data.history) {
        const formattedMessages = historyResult.data.history.map((msg, index) => ({
          id: index,
          type: msg.role,
          content: msg.content,
          timestamp: msg.timestamp,
          searchUsed: msg.search_used || false,
          searchEngine: msg.search_engine || null,
          personalizationUsed: msg.personalization_used || false,
          deepThinkingUsed: msg.deep_thinking_used || false,
        }));
        setMessages(formattedMessages);
      } else {
        setMessages([]);
      }
    } catch (error) {
      console.error('加载会话历史失败:', error);
      setMessages([]);
    }
  };

  // 当前会话变化时加载历史
  useEffect(() => {
    loadSessionHistory(currentSessionId);
  }, [currentSessionId]);

  // 会话选择处理
  const handleSessionSelect = (session) => {
    // 如果传入的是session对象，提取id；如果是null，直接使用
    const sessionId = session ? session.id : null;
    setCurrentSessionId(sessionId);
  };

  // 创建新会话
  const handleNewSession = () => {
    setCurrentSessionId(null);
    setMessages([]);
  };

  // 处理会话创建后的回调
  const handleSessionCreate = (session) => {
    if (session && session.id) {
      setCurrentSessionId(session.id);
      setMessages([]);
    }
  };

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputMessage.trim() || loading) {
      return;
    }

    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: inputMessage.trim(),
      timestamp: new Date().toLocaleString(),
    };

    // 添加用户消息
    setMessages(prev => [...prev, userMessage]);
    const currentMessage = inputMessage.trim();
    setInputMessage('');
    setLoading(true);

    try {
      // 发送消息到后端
      const result = await chatService.sendMessage(currentMessage, currentSessionId, enableSearch, 'tavily', enablePersonalization, enableDeepThinking);
      
      if (result.success) {
        const aiMessage = {
          id: Date.now() + 1,
          type: 'assistant',
          content: result.data.response,
          timestamp: result.data.timestamp,
          searchUsed: result.data.search_used,
          searchEngine: result.data.search_engine,
          personalizationUsed: result.data.personalization_used,
          deepThinkingUsed: result.data.deep_thinking_used,
        };
        setMessages(prev => {
          const newMessages = [...prev, aiMessage];
          // 如果是已有会话的第一次对话（现在有2条消息：用户消息+AI回复），触发刷新
          if (currentSessionId && newMessages.length === 2) {
            // 延迟触发刷新，确保后端已完成会话标题生成
            setTimeout(() => {
              setSessionListRefreshTrigger(prev => prev + 1);
            }, 500);
          }
          return newMessages;
        });
        
        // 如果是新会话，更新当前会话ID并刷新会话列表
        if (!currentSessionId && result.data.session_id) {
          setCurrentSessionId(result.data.session_id);
          // 触发会话列表刷新
          setSessionListRefreshTrigger(prev => prev + 1);
        }
      } else {
        // 显示错误消息
        const errorMessage = {
          id: Date.now() + 1,
          type: 'assistant',
          content: `抱歉，${result.message}`,
          timestamp: new Date().toLocaleString(),
          isError: true,
        };
        setMessages(prev => [...prev, errorMessage]);
        message.error(result.message);
      }
    } catch (error) {
      console.error('发送消息异常:', error);
      const errorMessage = {
        id: Date.now() + 1,
        type: 'assistant',
        content: '抱歉，发生了未知错误，请稍后重试。',
        timestamp: new Date().toLocaleString(),
        isError: true,
      };
      setMessages(prev => [...prev, errorMessage]);
      message.error('发送消息失败');
    } finally {
      setLoading(false);
      // 重新聚焦输入框
      setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
    }
  };

  // 清空聊天历史
  const handleClearHistory = async () => {
    if (!currentSessionId) {
      message.warning('请先选择一个会话');
      return;
    }
    
    try {
      const result = await chatService.clearChatHistory(currentSessionId);
      if (result.success) {
        setMessages([]);
        message.success('当前会话历史已清空');
      } else {
        message.error(result.message);
      }
    } catch (error) {
      console.error('清空历史失败:', error);
      message.error('清空历史失败');
    }
  };

  // 处理回车发送
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 渲染消息项
  const renderMessage = (msg) => {
    const isUser = msg.type === 'user';
    const isError = msg.isError;
    
    return (
      <div
        key={msg.id}
        className={`message-item ${isUser ? 'user-message' : 'ai-message'} ${isError ? 'error-message' : ''}`}
      >
        <div className="robot-avatar" >
          {isUser ? '💫' : '🤖'}
        </div>
        <div className="message-content">
          <div className="message-header">
            <span className="message-sender">
              {isUser ? '我' : 'CineMind AI助手'}
            </span>
            <span className="message-time">{msg.timestamp}</span>
            {msg.searchUsed && (
              <Tag color="blue" icon={<SearchOutlined />} size="small">
                搜索增强
              </Tag>
            )}
            {msg.personalizationUsed && (
              <Tag color="red" icon={<HeartOutlined />} size="small">
                个性化
              </Tag>
            )}
          </div>
          <div className="message-text">
            {isUser ? (
              msg.content
            ) : (
              <div className="markdown-content">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{msg.content}</ReactMarkdown>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="chatbot">
      <div className="chatbot-layout">
        {/* 会话列表面板 */}
        <SessionList
          visible={sessionListVisible}
          onSessionSelect={handleSessionSelect}
          onSessionCreate={handleSessionCreate}
          onNewSession={handleNewSession}
          currentSessionId={currentSessionId}
          refreshTrigger={sessionListRefreshTrigger}
          onClose={() => setSessionListVisible(false)}
        />
        
        {/* 主聊天区域 */}
        <div className={`chat-main ${sessionListVisible ? 'with-sidebar' : 'full-width'}`}>
          <div className="chat-header">
            <div className="chat-header-left">
              <Button
                type="text"
                icon={sessionListVisible ? <MenuFoldOutlined /> : <MenuOutlined />}
                onClick={() => setSessionListVisible(!sessionListVisible)}
                className="sidebar-toggle"
              />
              <Title level={2} style={{ margin: 0 }}>
                <MessageOutlined style={{ color: '#6a93ff' }} /> 智能对话
              </Title>
            </div>
          </div>
          
          <Card className="chat-container">

        {/* 消息列表 */}
        <div className="messages-container">
          {messages.length === 0 ? (
            <div className="empty-state-container">
              <Empty 
                description="欢迎使用 CineMind AI"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              >
                <p style={{ color: '#999', fontSize: 18, marginBottom: 8 }}>
                  您的专属智能影视推荐助手
                </p>
                <p style={{ color: '#666', fontSize: 14 }}>
                  {(() => {
                    const modes = [];
                    if (enableSearch) modes.push('搜索模式');
                    if (enablePersonalization) modes.push('个性化模式');
                    if (enableDeepThinking) modes.push('深度思考');
                    
                    if (modes.length > 0) {
                      return `${modes.join('和')}已开启，开始探索精彩影视世界吧！`;
                    }
                    return '开始探索精彩影视世界，发现您的专属推荐！';
                  })()}
                </p>
              </Empty>
            </div>
          ) : (
            <div className="messages-list">
              {messages.map(renderMessage)}
              {loading && (
              <div className="message-item ai-message">
                <div className="robot-avatar">
                  🤖
                </div>
                <div className="message-content">
                  <div className="message-header">
                    <span className="message-sender">CineMind AI小助手</span>
                    <span className="message-time">正在思考...</span>
                    {enableSearch && (
                      <Tag color="blue" icon={<SearchOutlined />} size="small">
                        搜索中
                      </Tag>
                    )}
                    {enablePersonalization && (
                      <Tag color="red" icon={<HeartOutlined />} size="small">
                        个性化分析中
                      </Tag>
                    )}
                    {enableDeepThinking && (
                      <Tag color="orange" icon={<BulbOutlined />} size="small">
                        深度思考中
                      </Tag>
                    )}
                  </div>
                  <div className="message-text">
                    <Spin size="small" /> {enableDeepThinking ? '正在深度思考中，请耐心等待（可能需要1-2分钟）...' : '正在生成回复...'}
                  </div>
                </div>
              </div>
            )}
              <div ref={messagesEndRef} />
            </div>
          )}
        </div>

        {/* 输入区域 */}
        <div className="input-container">
          <div className="floating-input-box">
            <div className="input-main">
              <TextArea
                ref={inputRef}
                value={inputMessage}
                onChange={(e) => setInputMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="按 Enter 发送，Shift + Enter 换行"
                autoSize={{ minRows: 1, maxRows: 4 }}
                className="floating-textarea"
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSendMessage}
                disabled={!inputMessage.trim()}
                className="floating-send-button"
              >
                发送
              </Button>
            </div>
            <div className="input-controls">
              <div className="control-buttons">
                <Tooltip title="启用搜索模式可以获取实时信息">
                  <Button
                    type={enableSearch ? "primary" : "text"}
                    icon={<SearchOutlined />}
                    size="small"
                    onClick={() => setEnableSearch(!enableSearch)}
                    className={`control-btn ${enableSearch ? 'active' : ''}`}
                  >
                    搜索
                  </Button>
                </Tooltip>
                
                <Tooltip title="启用个性化模式，基于用户画像提供定制化推荐">
                  <Button
                    type={enablePersonalization ? "primary" : "text"}
                    icon={<HeartOutlined />}
                    size="small"
                    onClick={() => setEnablePersonalization(!enablePersonalization)}
                    className={`control-btn ${enablePersonalization ? 'active' : ''}`}
                  >
                    个性化
                  </Button>
                </Tooltip>
                
                <Tooltip title="启用深度思考模式，提供更深入的分析（处理时间较长，可能需要1-2分钟）">
                  <Button
                    type={enableDeepThinking ? "primary" : "text"}
                    icon={<BulbOutlined />}
                    size="small"
                    onClick={() => setEnableDeepThinking(!enableDeepThinking)}
                    className={`control-btn ${enableDeepThinking ? 'active' : ''}`}
                  >
                    深度思考
                  </Button>
                </Tooltip>
                
                <Tooltip title="清空聊天历史">
                  <Button
                    type="text"
                    icon={<ClearOutlined />}
                    size="small"
                    onClick={handleClearHistory}
                    className="control-btn clear-btn"
                  >
                    清空历史
                  </Button>
                </Tooltip>
              </div>
            </div>
          </div>
        </div>
      </Card>
        </div>
      </div>
    </div>
  );
};

export default ChatBot;